package org.example.zookeeper.service;

import com.alibaba.fastjson.JSONObject;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.example.zookeeper.zk.ZookeeperRegistryCenter;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class SwitchDatasourceService {

    private JdbcTemplate jdbcTemplate;

    private ZookeeperRegistryCenter zookeeperRegistryCenter;

    public SwitchDatasourceService(ZookeeperRegistryCenter zookeeperRegistryCenter,
                                   JdbcTemplate jdbcTemplate) {
        this.zookeeperRegistryCenter = zookeeperRegistryCenter;
        this.jdbcTemplate = jdbcTemplate;
    }

    @PostConstruct
    public void postConstruct() throws Exception{

        String path = "/";

        //注册监听器
        //注册监听器
        zookeeperRegistryCenter.addCacheData(path);
        NodeCache nodeCache = zookeeperRegistryCenter.getNodeCache(path);
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                HikariDataSource oldHikariDataSource = (HikariDataSource)jdbcTemplate.getDataSource();
                oldHikariDataSource.close();

                //
                HikariDataSource newHikariDataSource = createHikariDataSource();
                jdbcTemplate.setDataSource(newHikariDataSource);

                System.out.println("监听到节点数据发生变化，重新设置Datasource。");
            }
        });
    }

    @PreDestroy
    public void preDestroy() {

    }

    private HikariDataSource createHikariDataSource() throws Exception{
        String path = "/";
        String datasource = zookeeperRegistryCenter.getDirectly(path);
        JSONObject jsonObject = JSONObject.parseObject(datasource);
        String driverClass = jsonObject.getString("driverClass");
        String jdbcUrl = jsonObject.getString("jdbcUrl");
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");

        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName(driverClass);
        hikariDataSource.setJdbcUrl(jdbcUrl);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);

        return hikariDataSource;
    }
}
